/**
 *
 */
package swt.commons;

import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.logging.FileHandler;
import java.util.logging.Handler;
import java.util.logging.Logger;
import java.util.logging.SimpleFormatter;

/**
 * LogUtil
 */
public class LogUtil {

	private static ArrayList pathList = new ArrayList();

	private static Logger logger = Logger.getLogger(LogUtil.class.getName());

	/**
	 * getLogger
	 * @return Logger
	 */
	public static Logger getLogger() {

		String logDir = "logs/";
		//
		if (!Utils.isNullEmpty(logDir)) {

			File forChk = new File(logDir);
			if (!forChk.exists()) {
				forChk.mkdirs();
				
			} else if (forChk.isFile()) {
				logger.severe(logDir + " not exist.");
			}

			String logFilePath = logDir + getLogFileName();

			if (!pathList.contains(logFilePath)) {
				logger.info("Log created = " + logFilePath);

				pathList = new ArrayList();
				pathList.add(logFilePath);

				Handler[] handlers = logger.getHandlers();
				if (handlers != null) {
					for (int i = 0; i < handlers.length; i++) {
						logger.removeHandler(handlers[i]);
					}
				}

				FileHandler fh = null;
				try {
					fh = new FileHandler(logFilePath, true);
				} catch (SecurityException e) {
					e.printStackTrace();
				} catch (IOException e) {
					e.printStackTrace();
				}
				SimpleFormatter formatter = new SimpleSimpleFormatter();
				fh.setFormatter(formatter);
				logger.addHandler(fh);
			}
		}

		return logger;
	}

	/**
	 * getLogFileName
	 * @return String
	 */
	public static String getLogFileName() {

		Calendar todayCal = Calendar.getInstance();
		SimpleDateFormat today = new SimpleDateFormat("yyyyMMdd");
		String logFilePath = today.format(todayCal.getTime()) + ".log";

		return logFilePath;
	}

	/**
	 * print message log to console
	 * @param msg
	 */
	public static void out(String msg){
		
		System.out.println(msg);
	}
}
